<script setup lang="ts">
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import dataQueryApi from '@/api/modules/data.query'

defineOptions({
  name: 'DeclearFileUpload',
})

const props = withDefaults(
  defineProps<{
    name?: UploadProps['name']
    size?: number
    max?: number
    files?: any[]
    notip?: boolean
    ext?: string[]
    readonly?: boolean
    isEx: boolean
  }>(),
  {
    name: 'file',
    size: 5,
    max: 10,
    files: () => [],
    notip: false,
    ext: () => [],
    readonly: false,
    isEx: false,
  },
)

const emits = defineEmits<{
  onSuccess: [
    res: any,
    file: UploadUserFile,
    fileList: UploadUserFile[],
  ]
}>()

const renderFiles = computed(() => {
  return props.files?.map((item) => {
    return {
      name: item.FileName,
      ...item,
    }
  })
})

const uploadRef = ref()
const tempData = ref<any>({})

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  // const fileName = file.name.split('.')
  // const fileExt = fileName.at(-1) ?? ''
  // const isTypeOk = props.ext.includes(fileExt)
  const isSizeOk = file.size / 1024 / 1024 < props.size
  // if (!isTypeOk) {
  //   ElMessage.error(`上传文件只支持 ${props.ext.join(' / ')} 格式！`)
  // }
  if (!isSizeOk) {
    ElMessage.error(`上传文件大小不能超过 ${props.size}MB！`)
  }
  // return isTypeOk && isSizeOk
  return isSizeOk
}

const onExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('文件上传超过限制')
}

const onSuccess: UploadProps['onSuccess'] = (res, file, fileList) => {
  emits('onSuccess', res, file, fileList)
}

function httpRequest(option: any) {
  if (!option.file) {
    return
  }
  if (props.isEx) {
    const formData = new FormData()
    formData.append('file', option.file)
    formData.append('produceObjId', tempData.value.ProduceObjID)
    formData.append('reusePartObjID', tempData.value.ReusePartObjID)
    formData.append('startTime', tempData.value.StartTime)
    return dataQueryApi.AddExDeclareFile(formData as any)
  }
  else {
    const formData = new FormData()
    formData.append('file', option.file)
    formData.append('declareID', tempData.value.DeclareID)
    return dataQueryApi.AddOverhaulDeclareFile(formData as any)
  }
}

function submit(data: any) {
  tempData.value = data
  uploadRef.value!.submit()
}

function onRemove(item: any) {
  const api = props.isEx ? dataQueryApi.DeleteExDeclareFile : dataQueryApi.DeleteOverhaulDeclareFile
  return api({ fileID: item.FileID }).then((res) => {
    ElMessage.success('删除成功')
    return res
  })
}

function preview(item: any) {
  if (!item.FileID) {
    return
  }
  const api = props.isEx ? dataQueryApi.GetExDeclareFile : dataQueryApi.GetOverhaulDeclareFile
  api({ fileID: item.FileID }).then((res) => {
    const url = window.URL.createObjectURL(res as Blob)
    const a = document.createElement('a')
    a.href = url
    a.target = '_blank'
    a.click()
  })
}

defineExpose({
  submit,
})
</script>

<template>
  <ElUpload
    ref="uploadRef"
    action="#"
    :before-upload="beforeUpload"
    :on-exceed="onExceed"
    :on-success="onSuccess"
    :on-preview="preview"
    :before-remove="onRemove"
    :file-list="renderFiles"
    :limit="max"
    :http-request="httpRequest"
    :auto-upload="false"
    :disabled="props.readonly"
  >
    <el-button v-if="!props.readonly" type="primary">
      选择附件
    </el-button>
  </ElUpload>
</template>

<style lang="scss" scoped>
:deep(.el-upload.is-drag) {
  display: inline-block;

  .el-upload-dragger {
    padding: 0;
  }

  &.is-dragover {
    border-width: 1px;
  }

  .slot {
    width: 300px;
    padding: 40px 0;
  }
}
</style>
